<?php
/**
 * 进程启动时，要做的事情
 */
declare(strict_types=1);

namespace Apps\Tcp\Services;

use Swoole\Server;
use Libraries\File;

class Init
{
    /**
     * 初始化的入口程序
     * @global Server $objTcpServer
     * @param int $intWorkerId
     * @return void
     */
    public static function go(int $intWorkerId): void
    {
        global $objTcpServer;
        /* 定时器 */
        $objTcpServer->after(1000 + $intWorkerId * 100, function () {
            self::saveWorkerData(); // 定时保存数据
        });
    }
    
    /**
     * 每300秒保存一次挂载的数据
     * @global Server $objTcpServer
     * @return void
     */
    private static function saveWorkerData(): void
    {
        global $objTcpServer;
        $objTcpServer->tick(300000, function () use ($objTcpServer) {
            is_array($objTcpServer->arrData) || $objTcpServer->arrData = [];
            File::writePhpData($objTcpServer->strDataFile, $objTcpServer->arrData, true);
        });
    }
}
